package com.jtny.nytb.datafilling.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jtny.component.dto.CurrentUserDTO;
import com.jtny.component.entity.LocalHolder;
import com.jtny.component.exception.ServiceException;
import com.jtny.component.util.BeanUtils;
import com.jtny.component.util.CurrentUserUtils;
import com.jtny.nytb.datafilling.dao.EnergyFillDAO;
import com.jtny.nytb.datafilling.dao.EnergyFillPriceDAO;
import com.jtny.nytb.datafilling.dao.EnergyModelDAO;
import com.jtny.nytb.datafilling.domain.EnergyFillDO;
import com.jtny.nytb.datafilling.domain.EnergyFillPriceDO;
import com.jtny.nytb.datafilling.domain.InstitutionEquipmentDO;
import com.jtny.nytb.datafilling.dto.*;
import com.jtny.nytb.datafilling.service.EnergyPriceConfigService;
import com.jtny.nytb.datafilling.vo.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 能源价格配置填报业务接口实现类，实现EnergyPriceConfigBiz
 *
 * @author 罗霄林
 * @package com.jtny.nytb.energymonitor.datafilling.biz.impl
 * @fileName EnergyPriceConfigServiceImpl.java
 * @createTime 2023年09月06日 00:00
 */
@Service
public class EnergyPriceConfigServiceImpl extends ServiceImpl<EnergyFillDAO, EnergyFillDO> implements EnergyPriceConfigService {

    @Resource
    private EnergyFillDAO energyFillDAO;

    @Resource
    private EnergyModelDAO energyModelDAO;

    @Resource
    private EnergyFillPriceDAO energyFillPriceDAO;

    @Resource
    InstitutionEquipmentServiceImpl institutionEquipment;

    private static final Calendar CALENDAR = Calendar.getInstance();

    @Override
    public Boolean saveEnergyPriceConfigInfo(EnergyPriceConfigParamVO energyPriceConfigParamVO) {
        EnergyPriceConfigParamDTO pecpDTO = new EnergyPriceConfigParamDTO();
        BeanUtils.copyObject(energyPriceConfigParamVO, pecpDTO);
        CurrentUserDTO currentUserDTO = LocalHolder.getCurrentUser();
        CurrentUserUtils.setCreateDefaultField(pecpDTO, currentUserDTO);
        pecpDTO.setFillName(currentUserDTO.getUsername());
        if (ObjectUtils.isNotEmpty(pecpDTO.getDataList())) {
            pecpDTO.getDataList().forEach(
                    epDTO -> CurrentUserUtils.setCreateDefaultField(epDTO, currentUserDTO)
            );
        }

        EnergyFillDO energyFillDO = new EnergyFillDO();
        BeanUtils.copyObject(pecpDTO, energyFillDO);
        //查询当月当前能源下的制度
        LambdaQueryWrapper<EnergyFillDO> institutionQueryWrapper = Wrappers.lambdaQuery(EnergyFillDO.class)
                .eq(EnergyFillDO::getTypeId, pecpDTO.getTypeId())
                .eq(EnergyFillDO::getMonth, String.valueOf(CALENDAR.get(Calendar.MONTH) + 1))
                .eq(EnergyFillDO::getYear, String.valueOf(CALENDAR.get(Calendar.YEAR)))
                .eq(EnergyFillDO::getInstitution, pecpDTO.getInstitution())
                .eq(EnergyFillDO::getName, pecpDTO.getName())
                .eq(Objects.nonNull(pecpDTO.getGroupName()),EnergyFillDO::getGroupName, pecpDTO.getGroupName());
        List<EnergyFillDO> institutionList = energyFillDAO.selectList(institutionQueryWrapper);
        if (ObjectUtils.isNotEmpty(institutionList)) {
            //删除制度
            List<Long> ids = institutionList.stream().map(EnergyFillDO::getId).collect(Collectors.toList());
            energyFillDAO.deleteBatchIds(ids);
            QueryWrapper<EnergyFillPriceDO> energyFillPriceWrapper = new QueryWrapper<>();
            energyFillPriceWrapper.lambda().in(EnergyFillPriceDO::getEnergyFillId,ids);
            energyFillPriceDAO.delete(energyFillPriceWrapper);

        }
        energyFillDO.setYear(LocalDate.now().getYear() + "");
        energyFillDO.setMonth(LocalDate.now().getMonth().getValue() + "");

        this.saveOrUpdate(energyFillDO);
        List<EnergyPriceDTO> dataList = pecpDTO.getDataList();
        if(CollectionUtil.isEmpty(dataList)){
            return true;
        }
        List<EnergyFillPriceDO> energyFillPriceDOS = BeanUtils.copyToList(dataList, EnergyFillPriceDO.class);
        energyFillPriceDOS.forEach(e->e.setEnergyFillId(energyFillDO.getId()));
        energyFillPriceDAO.insertBatch(energyFillPriceDOS);
        return Boolean.TRUE;
    }

    @Override
    public List<HistoryEnergyPriceVO> queryHistoryEnergyPriceConfigInfo(HistoryEnergyPriceParamVO historyEnergyPriceParamVO) {
        HistoryEnergyPriceParamDTO heppDTO = new HistoryEnergyPriceParamDTO();
        BeanUtils.copyObject(historyEnergyPriceParamVO, heppDTO);
        List<HistoryEnergyPriceDTO> list = energyFillDAO.queryHistoryEnergyPriceData(heppDTO);
        List<HistoryEnergyPriceVO> hepList = new ArrayList<>();
        list.forEach(
                hepDTO -> {
                    HistoryEnergyPriceVO hepVO = new HistoryEnergyPriceVO();
                    BeanUtils.copyObject(hepDTO, hepVO);
                    List<EnergyFillPriceDO> dataList = hepDTO.getDataList();
                    if(CollectionUtil.isNotEmpty(dataList)){
                        dataList.stream().filter(e->e.getColumnValue() != null)
                                .forEach(e->e.setColumnValue(e.getColumnValue().setScale(6, RoundingMode.HALF_UP)));
                        hepVO.setDataList(BeanUtils.copyToList(dataList, DataVO.class));
                    }
                    hepList.add(hepVO);
                }
        );
        return hepList;
    }

    @Override
    public void saveOrUpdateRealtion(List<InstitutionEquipmentVO> list) {

        List<InstitutionEquipmentDTO> list1 = BeanUtils.copyToList(list, InstitutionEquipmentDTO.class);

        if(CollectionUtil.isNotEmpty(list1)){
            Set<Long> eqids =
                    list1.stream().filter(e -> Objects.nonNull(e.getEquipmentId()))
                            .map(InstitutionEquipmentDTO::getEquipmentId).collect(Collectors.toSet());

            if(CollectionUtil.isEmpty(eqids)){
                return;
            }
            QueryWrapper<InstitutionEquipmentDO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(InstitutionEquipmentDO::getEquipmentId,eqids);
            List<InstitutionEquipmentDO> listDup = institutionEquipment.list(queryWrapper);
            if(CollectionUtil.isNotEmpty(listDup)){
                Map<String, List<InstitutionEquipmentDO>> insuByEqIdMap =
                        listDup.stream().collect(Collectors.groupingBy(e->e.getEquipmentId()+"/"+e.getYear()+"/"+e.getMonth()));

                list1.forEach(e->{
                    List<InstitutionEquipmentDO> institutionEquipmentDOS = insuByEqIdMap.get(e.getEquipmentId()+"/"+e.getYear()+"/"+e.getMonth());
                    if(CollectionUtil.isNotEmpty(institutionEquipmentDOS) && !institutionEquipmentDOS.get(0).getId().equals(e.getId())){
                        throw new ServiceException("存在已经关联的设备："+ e.getEquipmentName());
                    }
                });
            }

            list1.forEach(e-> e.setContainIns(StringUtils.isEmpty(e.getGroupName()) ? "1" : "0"));
            institutionEquipment.saveOrUpdateBatch(BeanUtils.copyToList(list,InstitutionEquipmentDO.class));
        }

    }



    @Override
    public void removeRealtion(List<Long> ids) {
        if(CollectionUtil.isNotEmpty(ids)){
            institutionEquipment.removeBatchByIds(ids);
        }
    }

    @Override
    public List<InstitutionEquipmentVO> getInstitutionEquipment(InstitutionEquipmentVO institutionEquipmentVO) {
        InstitutionEquipmentDTO institutionEquipmentDTO = BeanUtils.copyToObject(institutionEquipmentVO,InstitutionEquipmentDTO.class);

        QueryWrapper<InstitutionEquipmentDO> queryWrapper = new QueryWrapper<>(BeanUtils.copyToObject(institutionEquipmentDTO,InstitutionEquipmentDO.class));
        List<InstitutionEquipmentDTO> institutionEquipmentDTOS = BeanUtils.copyToList(institutionEquipment.list(queryWrapper),InstitutionEquipmentDTO.class);

        return BeanUtils.copyToList(institutionEquipmentDTOS,InstitutionEquipmentVO.class);
    }
}
